package cn.da.shuai.cool.ai.search.client.controller;

import cn.da.shuai.cool.ai.search.client.domain.resp.SearchResultResp;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.Setter;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/searxng")
public class SearxngController {

    @Value("${searxng.url}")
    private String url;

    @Value("${searxng.count}")
    private Integer count;

    @Setter(onMethod_ = @Autowired)
    private OkHttpClient okHttpClient;

    @GetMapping("/search")
    public List<SearchResultResp> search(String q) {
        HttpUrl url = HttpUrl.get(this.url)
                .newBuilder()
                .addQueryParameter("q", q)
                .addQueryParameter("format", "json")
                .build();
        Request request = new Request.Builder().url(url).addHeader("Cookie", """
                categories=general; language=auto; locale=zh-Hans-CN; autocomplete=; favicon_resolver=; image_proxy=0; safesearch=0; theme=simple; results_on_new_tab=0; doi_resolver=oadoi.org; simple_style=auto; center_alignment=0; advanced_search=0; query_in_title=0; infinite_scroll=0; search_on_category_select=1; hotkeys=default; url_formatting=pretty; disabled_engines="wikipedia__general\\054currency__general\\054wikidata__general\\054duckduckgo__general\\054google__general\\054lingva__general\\054startpage__general\\054dictzone__general\\054mymemory translated__general\\054brave__general"; enabled_engines="baidu__general\\054bing__general\\054sogou__general"; disabled_plugins=; enabled_plugins=; tokens=; method=POST""").build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("Unexpected code " + response.code());
            }
            if (response.body() != null) {
                JSONObject responseJson = JSON.parseObject(response.body().string());
                List<SearchResultResp> results = JSON.parseArray(JSON.toJSONString(responseJson.get("results")), SearchResultResp.class);

                return results.subList(0, Math.min(count, results.size()));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return List.of();
    }
}
